package com.limiter;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 计数器限流
 */
public class CounterLimiter {
    //起始时间
    private static long startTime = System.currentTimeMillis();
    //间隔时间
    private static long interval=1000;
    //每个时间间隔，限制数量
    private static  long limit=3;
    //累加器
    private static AtomicLong accumulator = new AtomicLong();

    public static boolean tryAcquire(){
        long currentTime = System.currentTimeMillis();
        //判断是覅在上一个时间间隔内
        if(currentTime<startTime+interval){
            //如果还在上一个时间间隔内
            long count = accumulator.incrementAndGet();
            if(count<=limit){
                return true;
            }else {
                return false;
            }
        }else {
            //如果不在上一个时间内
            synchronized (CounterLimiter.class){
                //防止重复初始化
                if(currentTime>startTime+interval){
                    startTime=currentTime;
                    accumulator.set(0);
                }
            }
            //再次判断
            long count = accumulator.incrementAndGet();
            if(count<=limit){
                return true;
            }else {
                return false;
            }
        }
    }
}
